from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.views import View
from rest_framework.response import Response
from rest_framework.views import APIView
# Create your views here.
from functools import wraps
from django.utils.decorators import method_decorator
from .serve import *


class regirst(APIView):
	def post(self, request):
		username = request.POST.get('username')
		password = request.POST.get('password')
		User.objects.create(username=username,password=password)
		res = {}
		res['code'] = 200
		res['message'] = '注册成功'
		return Response(res)

class login(APIView):
	def post(self, request):
		username = request.POST.get('username')
		password = request.POST.get('password')
		if User.objects.filter(username=username,password=password).first():
			res = {}
			res['code'] = 200
			res['message'] = '登录失败'
			return Response(res)
		else:
			res = {}
			res['code'] = 400
			res['message'] = '登录失败'
			return Response(res)


""" -------------------------------------------------------------  """


class GoodsAPI(APIView):
	def get(self, request):
		goods = Goods.objects.all()
		goods_ser = GoodsSer(goods, many=True)

		return Response({
			'data': goods_ser.data
		})


# 获取作者信息
class GetAuthor(APIView):
	def get(self, request):
		author = Author.objects.all()
		author_ser = AuthorSer(author, many=True)

		return Response({
			'data': author_ser.data
		})


# 添加图书
class AddBook(APIView):
	def get(self, request):
		name = request.GET.get('name')
		price = request.GET.get('price')
		authorid = request.GET.get('id')

		# print(name,price,authorid)
		author = Author.objects.get(id=int(authorid))
		Book.objects.create(name=name, price=price, author=author)

		return Response({
			'data': '添加成功'
		})


# 获取图书信息
class GetBook(APIView):
	def get(self, request):
		book = Book.objects.all()
		book_ser = BookSer(book, many=True)

		return Response({
			'data': book_ser.data
		})


# 删除图书
class DelBook(APIView):
	def get(self, request):
		id = request.GET.get('id')
		book = Book.objects.get(id=int(id))
		book.delete()

		return Response({
			'data': '删除成功'
		})
